package com.sikulifang.bank.simulation.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.script.ScriptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * 业务报文入口
 *
 * @author zhoul
 * @since 1.0.0
 */
@Slf4j
@RestController
public class MainController {

    static {
        System.setProperty("nashorn.args", "--language=es6");
    }

    private ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @GetMapping("/ping")
    @SuppressWarnings("all")
    public String ping() {
        return "ok";
    }

    @GetMapping("/access")
    public Object access() {
        ScriptEngine sc = ScriptUtil.createJsEngine();
        Dict dict = Dict.create();
        dict.set("a", "aaaaaaaa");
        dict.set("b", "bbbbbbbb");
        long time = System.currentTimeMillis();
        try {

            File file = ResourceUtils.getFile("D:\\Work\\sikulifang\\bank-simulation\\src\\main\\resources\\script" +
                                              "\\abc/balance.js");
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),
                    StandardCharsets.UTF_8))) {
                String mozillaCompat = "load('nashorn:mozilla_compat.js');";
                String code = bufferedReader.lines().collect(Collectors.joining(System.lineSeparator()));
                sc.put("d", dict);
                sc.put("applicationContext", applicationContext);
                Object eval = sc.eval(mozillaCompat + code);
                Invocable invocable = null;
                if (eval instanceof Invocable) {
                    invocable = (Invocable) eval;
                } else if (sc instanceof Invocable) {
                    invocable = (Invocable) sc;
                }

                if (invocable != null) {
                    return invocable.invokeFunction("start");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(System.currentTimeMillis() - time);
        }
        return "ok";
    }
}
